import java.util.TreeMap;

public class Solution2104 {


    class RangeHelper{

        int[][] rangeMinArr;

        int[][] rangeMaxArr;

        public RangeHelper(int[] nums){
            int n = nums.length;
            rangeMaxArr = new int[n][n];
            rangeMinArr = new int[n][n];
            for (int i = 0; i < n; i++) {
                rangeMaxArr[i][i] = rangeMinArr[i][i] = nums[i];
                for (int j = i + 1; j < n; j++) {
                    Integer tmpNum = nums[j];
                    rangeMaxArr[i][j] = Math.max(rangeMaxArr[i][j - 1], tmpNum);
                    rangeMinArr[i][j] = Math.min(rangeMinArr[i][j - 1], tmpNum);
                }
            }
        }

        public long getRange(int l, int r){
            return rangeMaxArr[l][r] - rangeMinArr[l][r];
        }
    }

    public long subArrayRanges(int[] nums) {
        long res = 0L;
        RangeHelper rangeHelper = new RangeHelper(nums);
        for (int i = 0; i < nums.length; i++) {
            for (int j = i + 1; j < nums.length; j++) {
                res += rangeHelper.getRange(i, j);
            }
        }
        return res;
    }
}
